#include "hal_eeprom.h"
#include "hal_position.h"
#include "hal_errorcode.h"
#include "i2c.h"
#include "sys_log.h"
#include "hal_EEpromWR.h"

void hal_AllMotorEEPromInformInit()
{
    EEPromInformSt EEPromInform;
    memset(&EEPromInform, 0, sizeof(EEPromInform));

    if (HAL_I2cEEPromRead(MOTOR_EEPROM_POSITION_ADDR, (uint8_t *)EEPromInform.Position, sizeof(EEPromInform)) != HAL_OK)
    {
        hal_ErrorCodeWrite(ERRORCODE_TYPE_COM_SYSTEM, s_EEProm_Rd_Abnormal_Flag, 0, ABNORMAL_STATE);
        SLOG_I("motor hal_AllMotorEEPromInformInit read error \t\r\n");
    }
    else
    {
        for (int i = 1; i <= MOTOR_MAX_ERROR_CHANNEL; i++)
        {
            for (int j = 1; j <= MOTOR_MAX_NUM; j++)
            {
                hal_PositionWrite(i, j, EEPromInform.Position[i - 1][j - 1]);
                if ((EEPromInform.StepState[i - 1][j - 1] < 1) || (EEPromInform.StepState[i - 1][j - 1] > 4))
                {
                    EEPromInform.StepState[i - 1][j - 1] = 1;
                }
                hal_StepStateWrite(i, j, EEPromInform.StepState[i - 1][j - 1]);
            }
        }
    }
}

void hal_AllMotorEEPromInformClear()
{
    EEPromInformSt EEPromInform;
    memset(&EEPromInform, 0xFF, sizeof(EEPromInform));

    if (HAL_I2cEEPromWrite(MOTOR_EEPROM_POSITION_ADDR, (uint8_t *)EEPromInform.Position, sizeof(EEPromInform)) != HAL_OK)
    {
        SLOG_I("motor hal_AllMotorEEPromInformClear error \t\r\n");
    }
}

// groupid:1~4    motor:1~8
void hal_SingleMotorEEPromInformWrite(uint8_t groupid, uint8_t motor_num, EEpStgTypeEn EEPromType)
{
    uint16_t offset = (groupid - 1) * MOTOR_MAX_ERROR_CHANNEL * 8 + (motor_num - 1) * sizeof(uint32_t);

    uint32_t stgvalue = (EEPromType == EEPSTGTYPE_POSITION) ? hal_PositionRead(groupid, motor_num) : hal_StepStateRead(groupid, motor_num);

    uint16_t eepromaddress = (EEPromType == EEPSTGTYPE_POSITION) ? (MOTOR_EEPROM_POSITION_ADDR + offset) : (MOTOR_EEPROM_STEP_ADDR + offset);

    HAL_StatusTypeDef eeprom_write_status = HAL_I2cEEPromWrite(eepromaddress, (uint8_t *)&stgvalue, sizeof(uint32_t));

    if (eeprom_write_status != HAL_OK)
    {
        hal_ErrorCodeWrite(ERRORCODE_TYPE_COM_SYSTEM, s_EEProm_Wt_Abnormal_Flag, 0, ABNORMAL_STATE);
        SLOG_I("motor hal_SingleMotorEEPromInformWrite %s Error \t\r\n", (EEPromType == EEPSTGTYPE_POSITION) ? "Position" : "StepState");
    }
}
